package com.itheima.controller;


import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/report/")
public class ReportController {
    @Reference(timeout = 7000)
    private MemberService memberService;

    @Reference(timeout = 7000)
    private SetmealService setmealService;

    @Reference(timeout = 7000)
    private ReportService reportService;

    @RequestMapping("getMemberReport")
    public Result getMemberReport(){
        return memberService.findMemberCount();
    }

    @RequestMapping("getSetmealReport")
    public Result getSetmealReport(){
        return setmealService.findSetMealCount();

    }

    @RequestMapping("getBusinessReportData")
    public Result getBusinessReportData(){
        try {
            Map<String, Object> businessReportData = reportService.getBusinessReportData();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,businessReportData);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);

        }
    }


    @RequestMapping("exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request,HttpServletResponse response){
        Map<String, Object> result = reportService.getBusinessReportData();
        //取出返回结果数据，准备将报表数据写入到Excel文件中
        String reportDate = (String) result.get("reportDate");
        Long todayNewMember = (Long) result.get("todayNewMember");
        Long totalMember = (Long) result.get("totalMember");
        Long thisWeekNewMember = (Long) result.get("thisWeekNewMember");
        Long thisMonthNewMember = (Long) result.get("thisMonthNewMember");
        Long todayOrderNumber = (Long) result.get("todayOrderNumber");
        Long thisWeekOrderNumber = (Long) result.get("thisWeekOrderNumber");
        Long thisMonthOrderNumber = (Long) result.get("thisMonthOrderNumber");
        Long todayVisitsNumber = (Long) result.get("todayVisitsNumber");
        Long thisWeekVisitsNumber = (Long) result.get("thisWeekVisitsNumber");
        Long thisMonthVisitsNumber = (Long) result.get("thisMonthVisitsNumber");
        List<Map<String,Object>> hotSetmeal = (List<Map<String, Object>>) result.get("hotSetmeal");

        String realPath = request.getServletContext().getRealPath("/template/report_template.xlsx");
        try (Workbook wb = WorkbookFactory.create(new FileInputStream(realPath))) {
            Sheet sheet = wb.getSheetAt(0);

            Row row = sheet.getRow(2);
            row.getCell(1).setCellValue(reportDate);

            row = sheet.getRow(4);
            row.getCell(1).setCellValue(todayNewMember);
            row.getCell(3).setCellValue(totalMember);

            row = sheet.getRow(5);
            row.getCell(1).setCellValue(thisWeekNewMember);
            row.getCell(3).setCellValue(thisMonthNewMember);

            row = sheet.getRow(7);
            row.getCell(1).setCellValue(todayOrderNumber);
            row.getCell(3).setCellValue(todayVisitsNumber);

            row = sheet.getRow(8);
            row.getCell(1).setCellValue(thisWeekOrderNumber);
            row.getCell(3).setCellValue(thisWeekVisitsNumber);

            row = sheet.getRow(9);
            row.getCell(1).setCellValue(thisMonthOrderNumber);
            row.getCell(3).setCellValue(thisMonthVisitsNumber);

            int rowNum =12;

            for (Map<String,Object> map : hotSetmeal) {
                row = sheet.getRow(rowNum++);

                row.getCell(0).setCellValue((String)map.get("name"));
                row.getCell(1).setCellValue((Long)map.get("setmeal_count"));
                row.getCell(2).setCellValue((BigDecimal)map.get("proportion")+"%");
                row.getCell(3).setCellValue((String)map.get("remark"));
            }

            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");

            wb.write(out);
            out.flush();
            out.close();
            return null;
        }catch(IOException e){
           e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    @RequestMapping("exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request,HttpServletResponse response){
        try{
            Map<String,Object> result = reportService.getBusinessReportData();

            //取出返回结果数据，准备将报表数据写入到Excel文件中
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            //动态获取pdf模板文件绝对磁盘路径
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";
            String jasperPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";

            //编译模板
            JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);

            //填充数据---使用JavaBean数据源方式填充
            JasperPrint jasperPrint =
                    JasperFillManager.fillReport(jasperPath,result,
                            new JRBeanCollectionDataSource(hotSetmeal));

            //创建输出流，用于从服务器写数据到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");

            //输出文件
            JasperExportManager.exportReportToPdfStream(jasperPrint,out);

            out.flush();
            out.close();

            return null;
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }


}
